<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home/welcome' }"
        >首页</el-breadcrumb-item
      >
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡形内容区域 -->
    <el-card class="box-card">
      <!-- 头部 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input
            placeholder="请输入内容"
            v-model.trim="usersInfo.query"
            clearable
            @clear="inpBtn"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchBtn"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 内容 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="switchBtn(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="amendBtn(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="deleteOpen(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                @click="assignRolesBtn(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="usersInfo.pagenum"
        :page-sizes="[1, 2, 4, 6]"
        :page-size="usersInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      @close="close"
    >
      <!-- 表单内容 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        status-icon
      >
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 表单尾 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserBtn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="amendVisible"
      width="50%"
      :before-close="amendBefore"
      @close="amendClose"
    >
      <el-form
        :model="amendForm"
        :rules="rules"
        ref="amendForm"
        label-width="100px"
        status-icon
      >
        <el-form-item label="用户名">
          <el-input v-model="amendForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="amendForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="amendForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="amendVisible = false">取 消</el-button>
        <el-button type="primary" @click="amendAffirmBtn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="assignRolesVisible"
      width="50%"
      @close="assignRolesClose"
    >
      <div>
        <p>当前的用户:{{ roleInfo.username }}</p>
        <p>当前的角色:{{ roleInfo.role_name }}</p>
        <p>
          分配新角色:
          <el-select v-model="assignRolesId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAssignRolesBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 用户列表数据Api
import {
  getUsersApi,
  getUsersAlterApi,
  getAddUsersApi,
  getUsersIdApi,
  getAmendUsersApi,
  getDeleteUsersIdApi,
  getRolesApi,
  getAssignRolesApi
} from '@/api/user.js'
export default {
  name: 'User',
  data() {
    // 验证邮箱的规则
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-]+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]))+/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的邮箱'))
    }
    // 验证手机号的规则
    const checkMobile = (rule, value, callback) => {
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的手机号'))
    }
    return {
      // 用户列表数据请求
      usersInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 用户列表数据
      userList: [],
      total: 0,
      // 显示隐藏添加用户框
      dialogVisible: false,
      // 添加用户表单的数据
      ruleForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单验证
      rules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 3, max: 11, message: '长度在 3 到 11 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 显示隐藏修改用户框
      amendVisible: false,
      // id查询到的用户数据对象
      amendForm: {},
      // 控制分配角色对话框的显示隐藏
      assignRolesVisible: false,
      // 需要分配的角色信息
      roleInfo: {},
      // 全部角色列表
      rolesList: [],
      // 已选中需要分配的角色id
      assignRolesId: ''
    }
  },
  created() {
    // 获取用户列表数据
    getUsersApi(this.usersInfo).then((res) => {
      if (res.data.meta.status === 200) {
        this.userList = res.data.data.users
        this.total = res.data.data.total
        this.$message.success('获取用户列表成功')
      } else {
        this.$message.error('获取用户列表失败')
      }
    })
  },
  methods: {
    // 监听pagesize改变的事件
    handleSizeChange(newSize) {
      this.usersInfo.pagesize = newSize
      getUsersApi(this.usersInfo).then((res) => {
        this.userList = res.data.data.users
        this.total = res.data.data.total
      })
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.usersInfo.pagenum = newPage
      getUsersApi(this.usersInfo).then((res) => {
        this.userList = res.data.data.users
        this.total = res.data.data.total
      })
    },
    // 修改用户状态
    switchBtn(val) {
      getUsersAlterApi({ uld: val.id, type: val.mg_state }).then((res) => {
        if (res.data.meta.status === 200) {
          this.$message.success('修改用户成功')
        } else {
          this.$message.error('修改用户失败')
          val.mg_state = !val.mg_state
        }
      })
    },
    // 查询功能
    searchBtn() {
      getUsersApi(this.usersInfo).then((res) => {
        this.userList = res.data.data.users
        this.total = res.data.data.total
      })
    },
    // 清空搜索页面刷新
    inpBtn() {
      getUsersApi(this.usersInfo).then((res) => {
        this.userList = res.data.data.users
        this.total = res.data.data.total
      })
    },
    // 按X关掉添加用户框触发
    handleClose() {
      this.dialogVisible = false
      this.$refs.ruleForm.resetFields()
    },
    // 关掉添加框后重置表单
    close() {
      this.$refs.ruleForm.resetFields()
    },
    // 点击添加用户的确认按钮
    addUserBtn() {
      // 此方式效验表单填下内容是否正确
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) return
        // 表单内容正确则发起请求
        getAddUsersApi(this.ruleForm).then((res) => {
          if (res.data.meta.status === 201) {
            this.$message.success('添加用户成功')
            // 关掉添加用户框
            this.dialogVisible = false
            // 刷新页面数据
            getUsersApi(this.usersInfo).then((res) => {
              this.userList = res.data.data.users
              this.total = res.data.data.total
            })
          } else {
            this.$message.error('添加用户失败')
          }
        })
      })
    },
    // 按X关掉修改用户框触发
    amendBefore() {
      this.amendVisible = false
    },
    // 点击修改按钮并根据id查询用户信息
    amendBtn(id) {
      this.amendVisible = true
      getUsersIdApi(id).then((res) => {
        if (res.data.meta.status === 200) {
          this.amendForm = res.data.data
          this.$message.success('查询用户数据成功')
        } else {
          this.$message.error('查询用户数据失败')
        }
      })
    },
    // 确定修改按钮并调用修改请求
    amendAffirmBtn() {
      this.$refs.amendForm.validate((valid) => {
        if (!valid) return
        // 表单内容正确则发起请求
        getAmendUsersApi(this.amendForm).then((res) => {
          if (res.data.meta.status === 200) {
            this.$message.success('修改用户成功')
            this.amendVisible = false
            // 更新页面数据
            getUsersApi(this.usersInfo).then((res) => {
              this.userList = res.data.data.users
              this.total = res.data.data.total
            })
          } else {
            this.$message.error('修改用户失败')
          }
        })
      })
    },
    // 关掉添加框后重置表单
    amendClose() {
      this.$refs.amendForm.resetFields()
    },
    // 点击删除按钮并确定是否删除用户
    deleteOpen(id) {
      this.$confirm('此操作将永久删除该用户信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          getDeleteUsersIdApi(id).then((res) => {
            if (res.data.meta.status === 200) {
              this.$message.success('删除成功')
              // 更新页面数据
              getUsersApi(this.usersInfo).then((res) => {
                this.userList = res.data.data.users
                this.total = res.data.data.total
              })
            } else {
              this.$message.error('删除失败')
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 分配角色按钮
    assignRolesBtn(roleInfo) {
      this.roleInfo = roleInfo
      // 获取角色列表信息
      getRolesApi().then((res) => {
        this.rolesList = res.data.data
      })
      this.assignRolesVisible = true
    },
    // 确定分配新角色按钮
    saveAssignRolesBtn() {
      if (!this.assignRolesId) {
        return this.$message.error('未选择新角色')
      }
      getAssignRolesApi(this.roleInfo.id, { rid: this.assignRolesId }).then(
        (res) => {
          console.log(res)
          this.assignRolesVisible = false
        }
      )
    },
    // 监听分配角色对话框关闭事件
    assignRolesClose() {
      this.assignRolesId = ''
    }
  }
}
</script>

<style lang='less' scoped>
.el-breadcrumb {
  margin-bottom: 15px;
}
.el-card {
  box-shadow: none !important;
}
.el-table {
  margin-top: 15px;
  font-size: 12px;
}

.el-pagination {
  margin-top: 15px;
}
</style>
